package com.yoo.ons.base.adpater

import androidx.lifecycle.LifecycleOwner
import com.yoo.module_base.base.Activities
import com.yoo.ons.ToastUtil.showToast
import com.yoo.ons.base.ServerException
import com.yoo.ons.base.bindLifecycle
import io.reactivex.observers.DisposableObserver
import java.net.SocketTimeoutException
import java.net.UnknownServiceException

open class ObserverAdapter<T>(owner: LifecycleOwner? = null) : DisposableObserver<T>() {
    init {
        bindLifecycle(owner)
    }

    override fun onComplete() {
    }

    override fun onNext(t: T & Any) {
    }

    override fun onError(e: Throwable) {
        e.printStackTrace()
        if (e is ServerException) {
            if (e.msg?.isNotEmpty() == true) {
                displayErrorMessage(e.msg)
            }
        } else if (e is retrofit2.adapter.rxjava2.HttpException ||
                e is retrofit2.HttpException) {
            if (e.message?.isNotEmpty() == true) {
                if (e.message?.contains("502") == true) {
                    displayErrorMessage("System maintenance")
                } else {
                    Activities.get().top?.let { displayErrorMessage(it.getString(com.yoo.module_res.R.string.network_err_tip)) }
                }
            }
        } else if (e is SocketTimeoutException) {
            Activities.get().top?.let { displayErrorMessage(it.getString(com.yoo.module_res.R.string.network_err_tip)) }
        } else if (e is java.net.UnknownHostException || e is UnknownServiceException) {
            Activities.get().top?.let { displayErrorMessage(it.getString(com.yoo.module_res.R.string.network_err_tip)) }
        }
    }

    private fun displayErrorMessage(msg: String) {
        //log("displayErrorMessage $msg")
        showToast(msg)
    }



}


